package com.csaba.connector.axa;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import com.csaba.connector.BankService;
import com.csaba.connector.I18NServiceException;
import com.csaba.connector.ServiceException;
import com.csaba.connector.axa.model.AXABank;
import com.csaba.connector.axa.model.AXASession;
import com.csaba.connector.model.Account;
import com.csaba.connector.model.Session;
import com.csaba.connector.service.AbstractBankService;

public class AXASelectAccountService extends AbstractBankService implements BankService, Codes
{
	//INPUT
	private Account account;

	//OUTPUT
	private int[] pinMask;

	@Override
	public void execute( final Session session ) throws ServiceException
	{
		if ( !( session instanceof AXASession ) )
			throw new ServiceException("Incompatible session " + AXABank.class + " != " + session.getClass().getName());
		if ( account == null )
			throw new ServiceException("Service is not yet inicialized.");

		final AXASession axa = (AXASession) session;

		//SELECT ACCOUNT
		/*
		 * AccountNumber=xxxxxxxx
		 */
		final NameValuePair[] selectAccountRequest = new NameValuePair[] {// 
		new BasicNameValuePair("AccountNumber", account.getNumber()),//
		};

		final String selectAccountResult = axa.doPost(AXASession.getRequestURL(REQUEST_SELECT_ACCOUNTS),
				selectAccountRequest);
		axa.debugFile("selectAccountResult", selectAccountResult);

		//result: [0,1,5]
		try
		{
			final JSONArray array = new JSONArray(selectAccountResult);
			pinMask = new int[array.length()];
			for ( int i = 0; i < pinMask.length; i++ )
			{
				pinMask[i] = array.getInt(i);
			}
		}
		catch ( final JSONException e )
		{
			throw new I18NServiceException(AXABank.getInstance(), "err.accountSelectFailed", e);
		}

		session.setRemoteProperty(RP_SELECTED_ACCOUNT, account);

	}

	public void setAccount( final Account account )
	{
		this.account = account;
	}

	public Account getAccount()
	{
		return account;
	}

	/**
	 * Pin mask will look like this {1,2,3}, containing indexes of pin digit to be captured.
	 * Digit pos indexed from 0.
	 * @return
	 */
	public int[] getPinMask()
	{
		return pinMask;
	}

}
